package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"taobao-merchandise/models/mysql"

	"taobao-merchandise/userrpc/internal/svc"
	"taobao-merchandise/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsUpdateLogic {
	return &GoodsUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改更新商品信息
func (l *GoodsUpdateLogic) GoodsUpdate(in *userrpc.GoodsUpdateRequest) (*userrpc.GoodsUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	if err := user.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}
	var findGoods mysql.Goods
	if err := findGoods.FindGoodsById(mysql.DB, in.GoodsId); err != nil {
		return nil, err
	}
	if findGoods.ID == 0 {
		return nil, errors.New("此商品不存在")
	}
	if in.UserId != findGoods.UserId {
		return nil, errors.New("无权限修改此商品")
	}
	goods := &mysql.Goods{
		Model:     gorm.Model{ID: uint(in.GoodsId)},
		UserId:    in.UserId,
		GoodsName: in.GoodsName,
		Price:     float64(in.Price),
		Stock:     in.Stock,
	}
	if err := goods.GoodsUpdate(mysql.DB); err != nil {
		return nil, err
	}
	return &userrpc.GoodsUpdateResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
